'use strict';
	angular.module('invoice.recSTDJSingle', [])

	.controller('recSTDJSingleCtrl'
			,['$rootScope', '$scope', 'systemService'
			  , 'uServiceCenter' ,'BizData', 'apiService'
			   , f])//控制器结束
	function f($rootScope,$scope, systemService
					   , uServiceCenter, BizData, apiService
					   ) {
		var common = require('common');
		
		var Model = this;
//		$scope.path = $rootScope.path;
//		$scope.createPermission = $rootScope.path + ':create';
		
		//定义页面级别的变量
		var systemCode = $rootScope.winid; //系统代码

		var flowType = 0;
		var billTypeName = "";
		var originName = "";

		var autoCode; //是否自动编码
		var revOpay; //入库出库
		var costingCode; //影响成本码
		
//		var storageType ;
//		var storageTypeLabel ;
//		var storageNo;
//		var storageName;
//		var floorNo;

		/////////////////////////////////////////////////////////////////////////////////////////////////

		var billType = 'STDJ';
		var direction = -1;
//		var departmentNo;
//		var departmentName;
		var employeeNo;
		var employeeName;

		var accountPaymentNo;
//		var writeOffNo;//核销批号
		
//		var maxDetailNo;

		var origin;

//		var factoryID;
//		var factoryNo;
//		var factoryName;
		
		var billNo;

		var state;
		var status;
		var audit;
		var orderDate;
		
		var userId;
		var enterpriseNo;
		var enterpriseName;
		
		var cUsercode;
		var cUsername;
		var cDatetime;
		
		var dealObject ='cus';
		var dealObjectLabel ='客户';
		var customerID;
		var customerNo;
		var shortName
		var customerName;
		
		var isMember;
		var memberNo;

		var clearType='D';
		var clearTypeLabel='D.退款核销';
		
		/**
		name:bizData#onNewCreateParam
		description: <b>[回调型事件]</b>业务新增数据创建新增参数事件，可以增加和修改用户自定义的参数
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"param" : {justep.Request.ActionParam} 新增参数对象,
			"defaultValues" : array - 新增行的默认值数组 ，数组的长度决定新增行数，数组中的对象是列的默认值
				defaultValues格式：
					[
						{列名:默认值,...},
						{列名:默认值,...},
						...
					]
		}
		</xmp>	
		@see justep.XData#newData
		@see justep.Request.ActionParam
		*/
		Model.dataMasterNewCreateParam = function(event) {
			event.param = {"billType": billType};
		}
		
		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataMasterBeforeNew = function(event) {

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataMasterAfterNew = function(event){
			//创建行后赋值
			event.source.setValue('systemCode',systemCode,event.id);
			
			event.source.setValue('dealObject',dealObject, event.id);
			event.source.setValue('dealObjectLabel',dealObjectLabel, event.id);
			
			event.source.setValue('orderAmount',0, event.id);
			
			event.source.setValue('clearType',clearType, event.id);
			event.source.setValue('clearTypeLabel',clearTypeLabel, event.id);
			
			event.source.setValue('handling', 'unclear', event.id);
			event.source.setValue('handlingLabel', '未核销', event.id);

			//产生自动流水号
			//获取初始化参数
			//获取单据参数
			var enterpriseNo = event.source.getValue("enterpriseNo", event.id);
			if(billType && enterpriseNo){
				var options = {};
				options.billType = billType;
				options.ognID = enterpriseNo;
				options.async = false;
				var billParam = systemService.getBillParam(options);
				if (billParam.state == "success"){
					event.source.setValue('dealType',billParam.dealType,event.id);
					event.source.setValue('billTypeName',billParam.billTypeName,event.id);
					event.source.setValue('flowType',billParam.flowType,event.id);
					event.source.setValue('origin', billParam.origin, event.id);	
					event.source.setValue('originName', billParam.originName, event.id);	
					event.source.setValue('revOpay', billParam.revOpay, event.id);	
					event.source.setValue('direction', billParam.direction, event.id);
					//event.source.setValue('costingCode', billParam.costingCode, event.id);	
					
					if (billParam.autoCode = "Y"){
						//产生自动流水号
						event.source.setValue('accountPaymentNo',billParam.billNo,event.id);
						event.source.setValue('originNo',billParam.billNo,event.id);
					}
				}else{
					systemService.dialogMsg('请在单据设置中进行初始化。');
				}
			}

		}

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataMasterBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataMasterAfterDelete = function(event) {
//			alert('删除之后！')
		}

		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataMasterIndexChanged = function(event) {
			if(event.rowID!=null){
				Model.dataDetail.fMasterID = event.rowID;
	       		Model.dataDetail.refreshData();
			}else{
				Model.dataDetail.clearData();
			}
		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataMasterDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataMasterValueChanged = function(event) {
			uServiceCenter.skfkMasterValueChanged(event);		
//			console.log('dataMasterValueChanged.event-->',event);
		}
		
		Model.dataMasterBeforeSave = function(event) {
			uServiceCenter.skfkMasterBeforeSave(event);
		}
		
		Model.dataMasterAfterSave = function(event) {
			
		}
		

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataDetailBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
//			event.cancel = true;
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataDetailAfterDelete = function(event) {
			uServiceCenter.skfkDetailAfterDelete(event);
		}
		
		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataDetailIndexChanged = function(event) {

		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataDetailDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataDetailValueChanged = function(event) {
			uServiceCenter.skfkDetailValueChanged(event);
		}
		

		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataDetailBeforeNew = function(event) {
			// 明细数据新增之前
			// 检查主表中的数据是否完整
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			
			state = dataMaster.getValue('state', rowID);
			status = dataMaster.getValue('status', rowID);
			audit = dataMaster.getValue('audit', rowID);
			orderDate = dataMaster.getValue('orderDate', rowID);
			
			//////////////////////////////////////////////////////////////////////
			systemCode = dataMaster.getValue('systemCode', rowID);
			//////////////////////////////////////////////////////////////////////

			// 判断如果那些为空，则拒绝新增明细数据
			customerID = dataMaster.getValue('customerID', rowID);
			customerNo = dataMaster.getValue('customerNo', rowID);
			shortName = dataMaster.getValue('shortName', rowID);
			customerName = dataMaster.getValue('customerName', rowID);
			
			isMember = dataMaster.getValue('isMember', rowID);
			memberNo = dataMaster.getValue('memberNo', rowID);
			
			if (customerNo == null || customerNo == "") {
				// 取消新增操作
//				alert('出入库部门不能为空！请先选择主表中的出入库部门，然后再在明细表中新增行。')
				event.cancel = true;
				systemService.dialogMsg('交易对象不能为空！请先选择主表中的交易对象，然后再在明细表中新增行。');
			}

			billType = dataMaster.getValue('billType', rowID);
			direction = dataMaster.getValue('direction', rowID);
//			departmentNo = dataMaster.getValue('departmentNo', rowID);
//			departmentName = dataMaster.getValue('departmentName', rowID);
			employeeNo = dataMaster.getValue('employeeNo', rowID);
			employeeName = dataMaster.getValue('employeeName', rowID);
			dealObject = dataMaster.getValue('dealObject', rowID);
			dealObjectLabel = dataMaster.getValue('dealObjectLabel', rowID);

			accountPaymentNo = dataMaster.getValue('accountPaymentNo', rowID);
//			writeOffNo = dataMaster.getValue('writeOffNo', rowID);
			
			//处理从表流水号
//			maxDetailNo=dataMaster.getValue('maxDetailNo', rowID);
//			maxDetailNo++;
//			var detailNo=common.preZeroFill(maxDetailNo, 5);
//			accountInvoiceDetailNo=accountInvoiceNo+detailNo;
				
			billTypeName = dataMaster.getValue('billTypeName', rowID);
			
			//////////////////////////////////////////////////////////////////////
			revOpay = dataMaster.getValue('revOpay', rowID);
			//////////////////////////////////////////////////////////////////////
			
			cUsercode = dataMaster.getValue('cUsercode', rowID);
			cUsername = dataMaster.getValue('cUsername', rowID);
			cDatetime = dataMaster.getValue('cDatetime', rowID);
			
			userId = dataMaster.getValue('userId', rowID);
			enterpriseNo = dataMaster.getValue('enterpriseNo', rowID);
			enterpriseName = dataMaster.getValue('enterpriseName', rowID);
			
			flowType = dataMaster.getValue('flowType', rowID);
			
//			clearType = dataMaster.getValue('clearType', rowID);
//			clearTypeLabel = dataMaster.getValue('clearTypeLabel', rowID);
				

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataDetailAfterNew = function(event){
			var dataDetail = event.source;
			var rowID = event.id;

			dataDetail.setValue('state', state, rowID);
			dataDetail.setValue('status', status, rowID);
			dataDetail.setValue('audit', audit, rowID);
			dataDetail.setValue('orderDate', orderDate, rowID);

//			dataDetail.setValue('billType', 'SKHX', rowID);
//			dataDetail.setValue('billTypeName', '收款核销', rowID);

			dataDetail.setValue('direction', direction, rowID);
//			dataDetail.setValue('departmentNo', departmentNo, rowID);
//			dataDetail.setValue('departmentName', departmentName, rowID);
			dataDetail.setValue('employeeNo', employeeNo, rowID);
			dataDetail.setValue('employeeName', employeeName, rowID);
			dataDetail.setValue('dealObject', dealObject, rowID);
			dataDetail.setValue('dealObjectLabel', dealObjectLabel, rowID);	

			dataDetail.setValue('customerID', customerID, rowID);
			dataDetail.setValue('customerNo', customerNo, rowID);
			dataDetail.setValue('shortName', shortName, rowID);
			dataDetail.setValue('customerName', customerName, rowID);
			
			dataDetail.setValue('isMember', isMember, rowID);
			dataDetail.setValue('memberNo', memberNo, rowID);

			dataDetail.setValue('accountPaymentNo', accountPaymentNo, rowID);

			////////////////////////////////////////////////////////////////////////////////////
			dataDetail.setValue('systemCode', systemCode, rowID);
			/////////////////////////////////////////////////////////////////////////////////////////
			

			
			////////////////////////////////////////////////////////////////////////////////////
			dataDetail.setValue('revOpay', revOpay, rowID);
			/////////////////////////////////////////////////////////////////////////////////////////
			
			//更新主表计数器（从表最大流水号）
//			var dataMaster = Model.dataMaster;
//			var masterRowID = dataMaster.getCurrentID();
//			dataMaster.setValue('maxDetailNo', maxDetailNo, masterRowID);	
			
			//更新主表中子表记录数
//			dataMaster.setValue('detailsCount', dataMaster.getValue('detailsCount', masterRowID) + 1, masterRowID);	

			dataDetail.setValue('cUsercode', cUsercode, rowID);
			dataDetail.setValue('cUsername', cUsername, rowID);
			dataDetail.setValue('cDatetime', cDatetime, rowID);

			dataDetail.setValue('userId', userId, rowID);
			dataDetail.setValue('enterpriseNo', enterpriseNo, rowID);
			dataDetail.setValue('enterpriseName', enterpriseName, rowID);

			dataDetail.setValue('fMasterID',dataDetail.fMasterID,rowID);
			dataDetail.setValue('flowType',flowType,rowID);
			
			dataDetail.setValue('clearType', clearType, rowID);
			dataDetail.setValue('clearTypeLabel', clearTypeLabel, rowID);
			
			dataDetail.setValue('handling', 'cleared', rowID);
			dataDetail.setValue('handlingLabel', '已核销', rowID);
			
		}

		
		
		
		
		

		///////////////////按钮组开始///////////////////////////////////////////////////
		//新建
		Model.add = function(){
			
		     var options = {
		         index : 0,
		         defaultValues : [
		             {
		            	 state:'active'
		            	 ,status:'open'
		            	 ,audit:'active'
		            	 
		            	 ,direction:direction
		            	 ,orderAmountTotal:0
		            	 ,pendingAmount:0
		            	 ,orderAmountCleared:0
		            	 ,discountCash:0
		            	 ,orderAmount:0//临时列
		            	 
		            	 ,accountAmountTotal:0
		            	 ,accountPending:0
		            	 ,accountAmountCleared:0
		            	 ,accountDiscount:0
		            	 
		            	 ,accountClearPayable:0
		            	 ,accountClearActual:0
		            	 ,accountDiscountPayable:0
		            	 
		            	 ,memberAmount:0
		            	 ,clearPrepayAmount:0
		            	 
		            	 ,accountDiscountCash:0
		            	 ,exchangeRate:0
		            	 ,entryFlag:0
		            	 ,cashSettle:0
		            	 ,retailFlag:0
		            		
		            	 ,resultStatus:'待审核'
		            	 ,paymentStatus:'待核销'
		            		
		            	 
		            	 ,billType: billType
		            	 ,orderDate: ':getCurrentDate()'
			             ,employeeNo: ':getCurrentPsmFID()'
				         ,employeeName: ':getCurrentPsmFName()'
			             ,cUsercode: ':getCurrentPersonCode()'
				         ,cUsername: ':getCurrentPersonName()'
					     ,cDatetime: ':getCurrentDateTime()'
						 ,userId: ':getCurrentPersonID()'
						 ,enterpriseNo: ':getCurrentOgnFID()'
						 ,enterpriseName: ':getCurrentOgnLongName()'
						 ,version: 0

			            }//,
//			             {itemNo:'a2',itemDescribe:'b2'}
			         ]
			     };    

			Model.dataMaster.newData(options);

			if($scope.tabpanel!='single'){
				$scope.tabpanel='single'
			}
		}
		
		//修改
		Model.edit = function(){
			Model.dataMaster.editData();
			if($scope.tabpanel!='single'){
				$scope.tabpanel='single'
			}
		}
		
		//保存
		Model.save = function() {
			Model.dataMaster.saveData();
		}

		//取消编辑
		Model.saveCancel = function() {
			Model.dataMaster.editCancel();
		}
		
		/*
		//不提示直接提交后台删除当前行
		var data = justp.xbl('mainData');
		var deleteConfirm = data.deleteConfirm;
		var directDeleteMode = data.directDeleteMode;
		try{
		    data.deleteConfirm = false;
		    data.directDeleteMode = true;
		    data.deleteData(data.getID());
		}finally{
		    data.deleteConfirm = deleteConfirm;
		    data.directDeleteMode = directDeleteMode;
		}
		*/
		Model.remove = function() {
			Model.dataMaster.deleteData(Model.dataMaster.getCurrentID());
			Model.dataMaster.refreshData();
		};
		
		//刷新
		Model.refresh = function() {
			Model.dataMaster.refreshData();
		}
		
		
		//输出：在浏览器窗口打开/下载打印（打印和导出）
		Model.printExport = function() {
			var options = {};
			options.path = $rootScope.getServiceName() + $rootScope.path + "/printPDF";
			options.id = Model.dataMaster.getCurrentID();
			if($rootScope.separation==0){
				//整体项目
				systemService.openPrintExportWindow(options); 
			}else{
				//前后端分离
				systemService.downloadExport(options); 
			}
		};

		///////////////////按钮组结束///////////////////////////////////////////////////
		///////////////////子表按钮组开始///////////////////////////////////////////////////
		//增加
		Model.addrow = function(){
		     var options = {
			         index : Model.dataDetail.getCount(),
			         defaultValues : [
			             {
			            	 state:'active'
			            	 ,status:'open'
			            	 ,audit:'active'
//			            	 ,orderDate:systemService.getCurrentDate(false)
				            	 
				             ,direction:direction
			            	 ,orderAmountTotal:0
			            	 ,pendingAmount:0
			            	 ,orderAmountCleared:0
			            	 ,discountCash:0
			            	 ,orderAmount:0//临时列
			            	 
			            	 ,accountAmountTotal:0
			            	 ,accountPending:0
			            	 ,accountAmountCleared:0
			            	 ,accountDiscount:0
			            	 
			            	 ,accountClearPayable:0
			            	 ,accountClearActual:0
			            	 ,accountDiscountPayable:0
			            	 
			            	 ,memberAmount:0
			            	 ,clearPrepayAmount:0
			            	 
			            	 ,accountDiscountCash:0
			            	 ,exchangeRate:0
			            	 ,entryFlag:0
			            	 ,cashSettle:0
			            	 ,retailFlag:0
			            		
			            	 ,resultStatus:'待审核'
			            	 ,paymentStatus:'待付款'
			            		
//			            	 ,detailsCount:0
//			            	 ,detailsCountState:0
//			            	 ,maxDetailNo:0
			            }//,
//			             {itemNo:'a2',itemDescribe:'b2'}
			         ]
			     };    

			Model.dataDetail.newData(options);
		}
		
		Model.delrow = function() {
			 if(Model.dataDetail.directDeleteMode){
				//直接删除
				 if(Model.dataDetail.deleteData(Model.dataDetail.getCurrentID())==0){
//					 Model.dataDetail.refreshData();
				 }
			 }else{
				//前台移除
				 if(Model.dataDetail.removeData(Model.dataDetail.getCurrentID())==0){
//					 Model.dataDetail.recordState = 'delete';
				 }
			 }
		};
		///////////////////子表按钮组结束///////////////////////////////////////////////////

		///////////////////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////////////////
		//打开对话框（选择交易对象）
		Model.triggerdealObjectNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var customerNo = dataMaster.getValue('customerNo', rowID);
     		if(customerNo!=null && customerNo!=''){
//         		dataMaster.setValue('dealObject', null, rowID);
//         		dataMaster.setValue('dealObjectLabel', null, rowID);
         		dataMaster.setValue('customerID', null, rowID);
         		dataMaster.setValue('customerNo', null, rowID);
         		dataMaster.setValue('shortName', null, rowID);
         		dataMaster.setValue('customerName', null, rowID);
     			return;
     		}
     		
     		var dealObject = dataMaster.getValue('dealObject', rowID);
     		//供应商
     		if(dealObject=='pro'){
     			Model.triggerProviderNoClick();
     		}
     		//人员
     		if(dealObject=='psn'){
     			Model.triggerPersonNoClick();
     		}
     		//客户
     		if(dealObject=='cus'){
     			Model.triggerCustomerNoClick();
     		}
		};
		
		//打开对话框（选择供应商）
		Model.triggerProviderNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
      		//供应商
			var options = {};
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			var modalInstance = systemService.openProviderNoDialog(options);
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
//	             		alert(returnData[i].sID+'-->'+returnData[i].sFName);
//	             		dataMaster.setValue('dealObject', returnData[i].storageTypeD, rowID);
//	             		dataMaster.setValue('dealObjectLabel', returnData[i].storageTypeDLabel, rowID);
	             		dataMaster.setValue('customerID', returnData[i].fID, rowID);
	             		dataMaster.setValue('customerNo', returnData[i].providerNo, rowID);
	             		dataMaster.setValue('shortName', returnData[i].shortName, rowID);
	             		dataMaster.setValue('customerName', returnData[i].providerName, rowID);
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		};
		
		//打开对话框（选择人员）
		Model.triggerPersonNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();

     		var options = {};
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			//是否显示人员
			options.psm = true;
			var modalInstance = systemService.openPersonOgnNoDialog(options);
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
//	             		alert(returnData[i].sID+'-->'+returnData[i].sFName);
//	             		dataMaster.setValue('dealObject', returnData[i].storageTypeD, rowID);
//	             		dataMaster.setValue('dealObjectLabel', returnData[i].storageTypeDLabel, rowID);
	             		dataMaster.setValue('customerID', returnData[i].personID, rowID);
	             		dataMaster.setValue('customerNo', returnData[i].sCode, rowID);
	             		dataMaster.setValue('shortName', returnData[i].sName, rowID);
	             		dataMaster.setValue('customerName', returnData[i].sLoginName, rowID);
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		};
		
		//打开对话框（选择客户）
		Model.triggerCustomerNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();

			var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

			var modalInstance = systemService.openCustomerNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
//	             		alert(returnData[i].sID+'-->'+returnData[i].sFName);
//	             		dataMaster.setValue('dealObject', returnData[i].storageTypeD, rowID);
//	             		dataMaster.setValue('dealObjectLabel', returnData[i].storageTypeDLabel, rowID);
	             		dataMaster.setValue('customerID', returnData[i].fID, rowID);
	             		dataMaster.setValue('customerNo', returnData[i].customerNo, rowID);
	             		dataMaster.setValue('shortName', returnData[i].shortName, rowID);
	             		dataMaster.setValue('customerName', returnData[i].customerName, rowID);
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		};
		///////////////////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////////////////
		
		//打开对话框（选择供应商）
		Model.triggerProviderNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var customerNo = dataMaster.getValue('customerNo', rowID);
     		if(customerNo!=null && customerNo!=''){
//         		dataMaster.setValue('dealObject', null, rowID);
//         		dataMaster.setValue('dealObjectLabel', null, rowID);
         		dataMaster.setValue('customerID', null, rowID);
         		dataMaster.setValue('customerNo', null, rowID);
         		dataMaster.setValue('shortName', null, rowID);
         		dataMaster.setValue('customerName', null, rowID);
     			return;
     		}

			var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

			var modalInstance = systemService.openCustomerNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
//	             		alert(returnData[i].sID+'-->'+returnData[i].sFName);
//	             		dataMaster.setValue('dealObject', returnData[i].storageTypeD, rowID);
//	             		dataMaster.setValue('dealObjectLabel', returnData[i].storageTypeDLabel, rowID);
	             		dataMaster.setValue('customerID', returnData[i].fID, rowID);
	             		dataMaster.setValue('customerNo', returnData[i].customerNo, rowID);
	             		dataMaster.setValue('shortName', returnData[i].shortName, rowID);
	             		dataMaster.setValue('customerName', returnData[i].customerName, rowID);

	             		dataMaster.setValue('isMember', returnData[i].isMember, rowID);
	             		dataMaster.setValue('memberNo', returnData[i].memberNo, rowID);
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		};
		
		//打开多选对话框（选择销售订单）
		Model.triggerOriginNoClick = function(){
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var customerID = dataMaster.getValue('customerID', rowID);
     		//截取供应商ID
     		if(customerID!=undefined && customerID!=''){
//     			customerID = customerID.substring(0,customerID.indexOf('/'));
     			customerID = customerID.substring(customerID.indexOf('/')+1,customerID.length);
//     			console.log('customerID-->',customerID);
     		}else{
     			alert('请先选择交易对象！');
     			return;
     		}

     		var originNo = dataMaster.getValue('originNo', rowID);
     		if(originNo!=null && originNo!=''){
         		dataMaster.setValue('originNo', null, rowID);
         		dataMaster.setValue('origin', null, rowID);
         		dataMaster.setValue('originName', null, rowID);
     			return;
     		}

     		var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);
     		var direction = dataMaster.getValue('direction', rowID);
			options.filter = "SaleOrder.customerID='"+customerID+"'"
			+" AND (SaleOrder.billType='XSDD')"
//			+" AND SaleOrder.direction="+direction
			;
			var modalInstance = systemService.openSaleOrderDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
				var returnData = event.data;
		    	for ( var i = 0; i < returnData.length; i++) {
		    		//新增行
		    		var simpleRow = returnData[i];

		    		dataMaster.setValue('origin', simpleRow.billType, rowID);
		    		dataMaster.setValue('originName', simpleRow.billTypeName, rowID);
		    		dataMaster.setValue('originNo', simpleRow.orderNo, rowID);

		    	}
	        	
	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};

		//打开对话框（选择经办人）
		Model.triggerEmployeeNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var employeeNo = dataMaster.getValue('employeeNo', rowID);
     		if(employeeNo!=null && employeeNo!=''){
         		dataMaster.setValue('employeeNo', null, rowID);
         		dataMaster.setValue('employeeName', null, rowID);
     			return;
     		}
			
			
			var options = {};
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			//是否显示人员
			options.psm = true;

			var modalInstance = apiService.openOrgNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
//	             		alert(returnData[i].sID+'-->'+returnData[i].sFName);
	             		dataMaster.setValue('employeeNo', returnData[i].sFID, rowID);
	             		dataMaster.setValue('employeeName', returnData[i].sFName, rowID);
	         			
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		}

		
		//打开对话框（选择资金账户）
		Model.triggerCapitalNoButtonClick = function(){
			
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			var capitalID = dataMaster.getValue('capitalID',rowID);
			if(capitalID!=null){
     			dataMaster.setValue('capitalID', null, rowID);
     			dataMaster.setValue('capitalNo', null, rowID);
     			dataMaster.setValue('capitalName', null, rowID);
     			dataMaster.setValue('capitalFullName', null, rowID);
     			return;
			}

			var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

			var modalInstance = systemService.openCaptionNoDialog(options);

	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;

     			dataMaster.setValue('capitalID', returnData[0].fID, rowID);
     			dataMaster.setValue('capitalNo', returnData[0].captionNo, rowID);
     			dataMaster.setValue('capitalName', returnData[0].captionName, rowID);
     			dataMaster.setValue('capitalFullName', returnData[0].captionFullName, rowID);

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		//打开对话框（选择会计科目）
		Model.triggerCaptionNoButtonClick = function(){
			
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			var captionID = dataMaster.getValue('captionID',rowID);
			if(captionID!=null){
     			dataMaster.setValue('captionID', null, rowID);
     			dataMaster.setValue('captionNo', null, rowID);
     			dataMaster.setValue('captionName', null, rowID);
     			dataMaster.setValue('captionFullName', null, rowID);
     			return;
			}

			var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);;

			var modalInstance = systemService.openCaptionNoDialog(options);

	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;

     			dataMaster.setValue('captionID', returnData[0].fID, rowID);
     			dataMaster.setValue('captionNo', returnData[0].captionNo, rowID);
     			dataMaster.setValue('captionName', returnData[0].captionName, rowID);
     			dataMaster.setValue('captionFullName', returnData[0].captionFullName, rowID);

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		
		//打开多选对话框（选择应付账款）
		Model.addrowsByPayable = function(){
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var customerID = dataMaster.getValue('customerID', rowID);
     		//截取供应商ID
     		if(customerID!=undefined && customerID!=''){
//     			customerID = customerID.substring(0,customerID.indexOf('/'));
     			customerID = customerID.substring(customerID.indexOf('/')+1,customerID.length);
     			console.log('customerID-->',customerID);
     		}else{
     			alert('请先选择交易对象！');
     			return;
     		}

     		var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);
     		var direction = dataMaster.getValue('direction', rowID);
			options.filter = "AccountInvoice.customerID='"+customerID+"'" 
					+ " AND AccountInvoice.direction="+direction 
					+ " AND ((AccountInvoice.billType='XSFP') OR (AccountInvoice.billType='QTYS' OR AccountInvoice.billType='HYCZ'))";
			var modalInstance = systemService.openInvoiceDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	        	var dataDetail = Model.dataDetail;
				var returnData = event.data;
		    	for ( var i = 0; i < returnData.length; i++) {
		    		//新增行
		    		Model.addrow();
		    		var simpleRow = returnData[i];
		    		
		    		var rowID = dataDetail.getCurrentID();
		    		
		    		if(simpleRow.billType=='XSFP'){
						dataDetail.setValue('billType', '1', rowID);
						dataDetail.setValue('billTypeName', '1.销售发票', rowID);
		    		}
		    		
		    		if(simpleRow.billType=='QTYS'){
						dataDetail.setValue('billType', '2', rowID);
						dataDetail.setValue('billTypeName', '2.其他应收', rowID);
		    		}

					dataDetail.setValue('systemCode', simpleRow.systemCode, rowID);

					dataDetail.setValue('origin', simpleRow.billType, rowID);
					dataDetail.setValue('originName', simpleRow.billTypeName, rowID);
					dataDetail.setValue('originNo', simpleRow.accountInvoiceNo, rowID);

//					dataDetail.setValue('billType', simpleRow.billType, rowID);
//					dataDetail.setValue('billTypeName', simpleRow.billTypeName, rowID);
//					dataDetail.setValue('accountInvoiceNo', simpleRow.accountInvoiceNo, rowID);
					
	     			dataDetail.setValue('settleCategory', simpleRow.invoiceCategory, rowID);
					dataDetail.setValue('settleCategoryLabel', simpleRow.invoiceCategoryLabel, rowID);
					dataDetail.setValue('settleCode', simpleRow.invoiceCode, rowID);
					dataDetail.setValue('settleDate', simpleRow.orderDate, rowID);
					dataDetail.setValue('captionFullNo', simpleRow.captionFullNo, rowID);
					dataDetail.setValue('captionFullName', simpleRow.captionFullName, rowID);

					dataDetail.setValue('orderAmount', simpleRow.orderAmountTotal, rowID);
					dataDetail.setValue('pendingAmount', simpleRow.pendingAmount, rowID);
					dataDetail.setValue('orderAmountCleared', simpleRow.pendingAmount, rowID);
		    	}
	        	
	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		//打开多选对话框（选择预付账款）
		Model.addrowsByPredict = function(){
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var customerID = dataMaster.getValue('customerID', rowID);
     		//截取供应商ID
     		if(customerID!=undefined && customerID!=''){
//     			customerID = customerID.substring(0,customerID.indexOf('/'));
     			customerID = customerID.substring(customerID.indexOf('/')+1,customerID.length);
     			console.log('customerID-->',customerID);
     		}else{
     			alert('请先选择交易对象！');
     			return;
     		}

     		var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);
     		var direction = dataMaster.getValue('direction', rowID);
			options.filter = "AccountPayment.customerID='"+customerID+"'" 
				+ " AND AccountPayment.billType='YSKD'"
				+ " AND AccountPayment.pendingAmount>0";
			var modalInstance = systemService.openPaymentDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	        	var dataDetail = Model.dataDetail;
				var returnData = event.data;
		    	for ( var i = 0; i < returnData.length; i++) {
		    		//新增行
		    		Model.addrow();
		    		var simpleRow = returnData[i];
		    		
		    		var rowID = dataDetail.getCurrentID();
		    		
					dataDetail.setValue('billType', '4', rowID);
					dataDetail.setValue('billTypeName', '4.冲减预收款', rowID);
//					dataDetail.setValue('billType', simpleRow.clearType, rowID);
//					if(simpleRow.clearType=='4'){
//						dataDetail.setValue('billTypeName', '4.冲减预收款', rowID);
//					}
//					if(simpleRow.clearType=='5'){
//						dataDetail.setValue('billTypeName', '5.冲减会员余额', rowID);
//					}
		    		
					dataDetail.setValue('systemCode', simpleRow.systemCode, rowID);

					dataDetail.setValue('origin', simpleRow.billType, rowID);
					dataDetail.setValue('originName', simpleRow.billTypeName, rowID);
					dataDetail.setValue('originNo', simpleRow.accountPaymentNo, rowID);

//					dataDetail.setValue('billType', simpleRow.billType, rowID);
//					dataDetail.setValue('billTypeName', simpleRow.billTypeName, rowID);
//					dataDetail.setValue('accountPaymentNo', simpleRow.accountPaymentNo, rowID);
					
	     			dataDetail.setValue('settleCategory', simpleRow.invoiceCategory, rowID);
					dataDetail.setValue('settleCategoryLabel', simpleRow.invoiceCategoryLabel, rowID);
					dataDetail.setValue('settleCode', simpleRow.settleCode, rowID);
					dataDetail.setValue('settleDate', simpleRow.orderDate, rowID);
					dataDetail.setValue('captionFullNo', simpleRow.captionFullNo, rowID);
					dataDetail.setValue('captionFullName', simpleRow.captionFullName, rowID);
					
					dataDetail.setValue('orderAmount', simpleRow.orderAmountTotal, rowID);
					dataDetail.setValue('pendingAmount', simpleRow.pendingAmount, rowID);
					dataDetail.setValue('orderAmountCleared', simpleRow.pendingAmount, rowID);
		    	}
	        	
	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		
		
		
		/////////////////////////////////////////////////////////////////////
		Model.triggerConfirmClick = function(event){
			//提交之前
			var options = new Object();
			options.bizData = Model.dataMaster;
			if(systemService.skfkConfirmBefore(options)==false){
				return;
			}
			// 提交单据
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/invoice/recSTDJ/single/confirm';
			systemService.operateBill(data);
		};
		Model.triggerActiveClick = function(event){
			// 撤销提交
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/invoice/recSTDJ/single/active';
			systemService.operateBill(data);
		};
		
		Model.triggerAgreeItClick = function(event){
			// 审核单据
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/invoice/recSTDJ/single/agreeIt';
			systemService.operateBill(data);
		};
		Model.triggerUnAgreeClick = function(event){
			// 撤销审核
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/invoice/recSTDJ/single/unAgree';
			systemService.operateBill(data);
		};
		
		Model.triggerCloseClick = function(event){
			// 关闭单据
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/invoice/recSTDJ/single/close';
			systemService.operateBill(data);
		};
		Model.triggerOpenClick = function(event){
			// 撤销审核
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/invoice/recSTDJ/single/open';
			systemService.operateBill(data);
		};

		///////////////////////////////////////////////////////////////////////////////
		
		
		//双击事件
		Model.gridListRowDblclick = function(rowIndex,rowID){
			$scope.tabpanel = 'single';
		}
		
		//打开关联单据
		Model.gridOriginNoClick = function(row){
//			console.log('row-->',row);
			var winParams = {
					"billNo":row.originNo.value
			};
			
			$rootScope.menuPreClick(row.systemCode.value,winParams);
		}
		

		/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//		Model.objects = {"dataMaster" : Model.dataMaster,"dataDetail" : Model.dataDetail};
		
		var options = {};
		options.container = Model;
		options.concept = 'AccountPayment';
		options.name = 'dataMaster';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '/invoice/recSTDJ/single/create';
		options.reader = '/invoice/recSTDJ/single/query';
		options.writer = '/invoice/recSTDJ/single/save';
		options.deleter = '/invoice/recSTDJ/single/delete';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = '';
		options.master = {"data":"","relation":""};
		options.directDeleteMode = true;
		options.limit = 15;
		options.orderBy = "cDatetime DESC";

		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataMasterIndexChanged;
		options.onBeforeNew = Model.dataMasterBeforeNew;
		options.onAfterNew = Model.dataMasterAfterNew;
		options.onBeforeDelete = Model.dataMasterBeforeDelete;
		options.onAfterDelete = Model.dataMasterAfterDelete;
		options.onValueChanged = Model.dataMasterValueChanged;
		options.onDataChanged = Model.dataMasterDataChanged;
		options.onBeforeSave = Model.dataMasterBeforeSave;
		options.onAfterSave = Model.dataMasterAfterSave;
		options.onNewCreateParam = Model.dataMasterNewCreateParam;
		
		Model.dataMaster = new BizData(options);
		//监视对象中的所有变动
		Model.dataMaster.deregRows = $scope.$watch('Model.dataMaster.rows',Model.dataMaster.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值

		
		
		var options = {};
		options.container = Model;
		options.concept = 'AccountPaymentDetail';
		options.name = 'dataDetail';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.reader = '/invoice/recSTDJ/single/queryDetail';
		options.creater = '/invoice/recSTDJ/single/createDetail';
		options.deleter = '';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = '';
		options.master = {"data":"dataMaster","relation":"fMasterID"};
		options.directDeleteMode = false;
		options.orderBy = 'cDatetime ASC';
		

		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataDetailIndexChanged;
		options.onBeforeNew = Model.dataDetailBeforeNew;
		options.onAfterNew = Model.dataDetailAfterNew;
		options.onBeforeDelete = Model.dataDetailBeforeDelete;
		options.onAfterDelete = Model.dataDetailAfterDelete;
		options.onValueChanged = Model.dataDetailValueChanged;
		options.onDataChanged = Model.dataDetailDataChanged;
		
		Model.dataDetail = new BizData(options);
		//监视对象中的所有变动
		Model.dataDetail.deregRows = $scope.$watch('Model.dataDetail.rows',Model.dataDetail.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		
		
		$scope.tabpanel = 'list';

		var winParams = $rootScope.winParams;
//		console.log('窗口打开时的参数1',winParams);
		if(winParams!=undefined && winParams!=null && winParams!=''){
			if(winParams.fID){
				Model.dataMaster.id = winParams.fID;
				$scope.tabpanel = 'single';
			}
			//隐藏/显示编辑工具条
//			if(winParams.type){
//				$scope.type = winParams.type;
//			}
			
			Model.dataMaster.refreshData();
		}else{
			
			//增加过滤器，只显示本人及本公司的数据
			Model.dataMaster.filter = "(AccountPayment.billType='STDJ')"
			;
			
			Model.dataMaster.refreshData();
//			console.log('Model.dataMaster.rows-->',Model.dataMaster.rows);
			
		}
		
	    return Model;
	}	
	
